package de.slothsoft.commons.swing.editorview;

import javax.swing.JPanel;

import de.slothsoft.commons.swing.databinding.DataBinding;
import de.slothsoft.commons.swing.validation.IValidationListener;
import de.slothsoft.commons.swing.validation.IValidationListener.ValidationEvent;
import de.slothsoft.commons.swing.validation.ValidationBinding;

public abstract class AbstractDataBindingEditor<E> extends
		AbstractTitleEditor<E> {

	private static final long serialVersionUID = 1L;

	private ValidationBinding validationBinding;
	private DataBinding<E> dataBinding;

	@Override
	protected final void createMainPanel(JPanel mainPanel) {
		this.validationBinding = new ValidationBinding();
		this.validationBinding.addListener(new IValidationListener() {

			@Override
			public void validationChanged(ValidationEvent event) {
				performValidationChanged(event);
			}
		});
		this.dataBinding = new DataBinding<E>(getModel());
		createMainPanel(mainPanel, this.dataBinding, this.validationBinding);
		this.dataBinding.updateTargets();
		this.validationBinding.validate();
	}

	protected abstract void createMainPanel(JPanel parent,
			DataBinding<E> dataBinding, ValidationBinding validation);

	protected void performValidationChanged(ValidationEvent event) {
		setErrorMessage(event.getErrorMessage());
	}

	public DataBinding<E> getDataBinding() {
		return this.dataBinding;
	}

	public ValidationBinding getValidationBinding() {
		return this.validationBinding;
	}

	@Override
	protected void updateControlsFromValue(E value) {
		this.dataBinding.updateTargets();
	}

	@Override
	protected void updateValueFromControls(E value) {
		this.dataBinding.updateModels();
	}

	@Override
	protected void setModel(E model) {
		super.setModel(model);
		this.dataBinding.setModel(model);
	}

}
